#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import glob
import json

from core.module_interfaces import TESTMODULE
from core.utils.tests import TestCommands


class TestInfo(TESTMODULE):
    def __init__(self):
        self.field_map = {
            'packages': ['name', 'version', 'arch', 'repo'],
        }

    def _collect_testinfo(self, test_instance, test_info_path):
        if os.path.isdir(test_info_path):
            return
        else:
            testcmd = TestCommands(test_instance.config)
            testcmd.collect_testinfo()

    def run(self, test_instance):
        testinfo_path = os.path.join(
            test_instance.config.result_runtime_path,
            'testinfo')

        statistic_file = os.path.join(
            test_instance.config.result_scenaria_path,
            'statistic.json'
        )

        self._collect_testinfo(test_instance, testinfo_path)

        statistic = {}
        with open(statistic_file) as fh:
            statistic = json.load(fh)

        updated = False
        for info_path in glob.glob(testinfo_path + "/*"):
            key = os.path.basename(info_path)
            with open(info_path) as fh:
                if key in self.field_map:
                    statistic['testinfo'][key] = []
                    for line in fh:
                        recorder = {}
                        for index, field in enumerate(self.field_map[key]):
                            value = line.split()
                            recorder[field] = value[index]
                        statistic['testinfo'][key].append(recorder)
                        updated = True
                else:
                    statistic['testinfo'][key] = "".join(fh.readlines())
                    statistic['testinfo'][key] = \
                        statistic['testinfo'][key].strip()
                    updated = True

        if updated:
            with open(statistic_file, 'w') as fh:
                json.dump(statistic, fh, indent=2, sort_keys=True)
